package team.yidong.fenda.utils;

import org.apache.commons.net.ftp.FTPClient;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.SocketException;

/**
 * Created by xuanlong on 2017/10/8.
 */
@Component
public class FtpUtil {

    /**
     * 获取ftp连接
     *
     * @return
     */
    public FTPClient getFTPClient(String ip,String userName,String password) {
        FTPClient ftpClient=null;
        try {
            ftpClient = new FTPClient();
            ftpClient.connect(ip);
            ftpClient.login(userName, password);
            ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE); // 设置上传文件以二进制上传
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ftpClient;
    }

    /**
     * 上传文件
     *
     * @param f 要上传的文件
     * @param  uploadDir 上传文件的路径
     * @return result 上传结果
     */
    public boolean putFile(FTPClient ftpClient,File f, String uploadDir) {
        boolean result = false;
        InputStream inputStream=null;
        try {
            try {
                ftpClient.changeWorkingDirectory(uploadDir);
                inputStream = new BufferedInputStream(new FileInputStream(f));
                result = ftpClient.storeFile(f.getName(), inputStream);
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }
}
